package com.bjhb.wuranyuan.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.bjhb.wuranyuan.common.Constant;
import com.bjhb.wuranyuan.pojo.User;

/**
 * Servlet Filter implementation class UserFilter
 */
public class UserFilter implements Filter {

	private List<String> authUrls;

	private String loginUrl;

	/**
	 * Default constructor.
	 */
	public UserFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		if (authUrls.contains(req.getServletPath())) {
			User user = (User) req.getSession().getAttribute(
					Constant.USER_SESSION);
			if (user == null) {
				resp.sendRedirect(req.getContextPath() + "/login.jsp");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		String authUrls = fConfig.getInitParameter("authUrls");
		if (!StringUtils.isEmpty(authUrls)) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(authUrls);
			String after = m.replaceAll("");
			String[] urls = after.split(",");

			this.authUrls = new ArrayList<String>();
			for (String url : urls) {
				this.authUrls.add(url);
			}
		}
		this.loginUrl = fConfig.getInitParameter("loginUrl");
	}

}
